/***********************************************************************
 * BinTrotter : BitTorrent library/client for the Android operating system.
 *  
 * Copyright (C) 2009, Christopher David Stones (chris.stones@gmail.com)
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 ***********************************************************************/

package org.bintrotter.apeer.sendstates;

import org.bintrotter.apeer.Peer;

public class Idle implements SendState {

	private Peer m_peer;
	private long m_idleTime;
	
	public Idle(Peer peer) {
		
		m_peer = peer;
	}
	
	@Override
	public void reset() {
	
		m_idleTime = System.currentTimeMillis();
	}

	@Override
	public States update() {
	
		
		// do we need to send an interested message ?
		if(m_peer.outShouldSendInterested())
			return States.INTERESTED;
		
		// do we need to send a not-interested message ?
		if(m_peer.outShouldSendNotInterested())
			return States.NOT_INTERESTED;
		
		// do we need to send a choke ? 
		if(m_peer.outShouldSendChoke())
			return States.CHOKE;
		
		// do we need to send an un-choke
		if(m_peer.outShouldSendUnchoke())
			return States.UNCHOKE;
		
		// do we need to send any cancel messages ?
		if(m_peer.outCancelQueue.peek() != null)
			return States.CANCEL;
		
		// do we need to send any piece requests messages ?
		if(m_peer.incommingBlocks != null) {
			
			int q = m_peer.incommingBlocks.queued();
			int t = m_peer.incommingBlocks.inTransit();
			
			if(q > 0 && t < 5) {
				return States.REQUEST;
			}
		}
			
		
		// to we need to send any piece messages ?
		if(m_peer.outPieceQueue.peek() != null)
			return States.PIECE;
		
		// do we need to send any have messages ?
		if(m_peer.outHaveQueue.peek() != null)
			return States.HAVE;

		// been idle for almost 2 minutes? send keep-alive 
		if(System.currentTimeMillis() - m_idleTime > 100000)
			return States.KEEP_ALIVE; 
		
		// nothing to do!
		return States.IDLE;
	}

}
